const webpack = require('atool-build/lib/webpack');
const path = require('path');
const glob = require('glob');
const pxtorem = require('postcss-pxtorem');

module.exports = function (webpackConfig, env) {
  webpackConfig.babel.plugins.push('transform-runtime');
  webpackConfig.babel.plugins.push(['import', {
    libraryName: 'antd-mobile',
    style: 'css',
  }]);

  // Support hmr
  if (env === 'development') {
    webpackConfig.devtool = '#eval';
    webpackConfig.babel.plugins.push('dva-hmr');
  } else {
    webpackConfig.babel.plugins.push('dev-expression');
  }

  // Don't extract common.js and common.css
  webpackConfig.plugins = webpackConfig.plugins.filter(function(plugin) {
    return !(plugin instanceof webpack.optimize.CommonsChunkPlugin);
  });

  webpackConfig.resolve.alias = {
    'lib': path.join(__dirname, 'src', 'utils'),
    'services': path.join(__dirname, 'src', 'services'),
    'modals': path.join(__dirname, 'src', 'modals'),
    'components': path.join(__dirname, 'src', 'components'),
    'routes': path.join(__dirname, 'src', 'routes'),
    'const': path.join(__dirname, 'src', 'constants'),
    'assets': path.join(__dirname, 'src', 'assets'),
  };

  // svg icon config
  const svgDirs = ['./src/assets/icons']; // 如果需要本地部署图标，需要在此加入本地图标路径，本地部署方式见以下文档
  // 把`antd-mobile/lib`目录下的 svg 文件加入进来，给 svg-sprite-loader 插件处理
  glob.sync('node_modules/**/*antd-mobile/lib', { dot: true }).forEach(p => {
    svgDirs.push(new RegExp(p));
  });

  // Support CSS Modules
  // Parse all less files as css module.
  webpackConfig.module.loaders.forEach(function(loader, index) {
    if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.less$/;
    }
    if (loader.test.toString() === '/\\.module\\.less$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.less$/;
    }
    if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.css$/;
    }
    if (loader.test.toString() === '/\\.module\\.css$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.css$/;
    }
    if (loader.test.toString() === '/\\.svg(\\?v=\\d+\\.\\d+\\.\\d+)?$/') {
      loader.exclude = svgDirs;
    }
  });

  // Note: https://github.com/kisenka/svg-sprite-loader/issues/4
  // Can not process SVG files twice. You need to make sure of it yourself.
  webpackConfig.module.loaders.unshift({
    test: /\.svg$/,
    loader: 'svg-sprite',
    include: svgDirs,
  });

  webpackConfig.postcss.push(pxtorem({
    rootValue: 100,
    propWhiteList: [],
  }));

  webpackConfig.externals = {
    'wx': 'jWeixin',
  };

  return webpackConfig;
};
